package xml;

import java.io.*;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import sqlServer.CryptString;



public class xmlSettings {

	File file = new File("settings/initSet.xml");
	Document doc;
	
	public xmlSettings() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		try {
			db = dbf.newDocumentBuilder();
			doc = db.parse(file);
			doc.getDocumentElement().normalize();
			System.out.println("Root element " + doc.getDocumentElement().getNodeName());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public String getLanguage(){
		return doc.getDocumentElement().getElementsByTagName("language").item(0).getFirstChild().getNodeValue();
	}
	
	public void setLanguage(String lang) throws Exception{
		doc.getDocumentElement().getElementsByTagName("language").item(0).removeChild(doc.getDocumentElement().getElementsByTagName("language").item(0).getFirstChild());
		doc.getDocumentElement().getElementsByTagName("language").item(0).appendChild(doc.createTextNode(lang));
		writeXmlToFile();
	}
	
	private void writeXmlToFile() throws Exception{
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        
        Writer outWriter = new StringWriter();
        StreamResult result =  new StreamResult(outWriter);
        transformer.transform(source, result);
        
        FileWriter xmlWebSetFileStream = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(xmlWebSetFileStream);
        out.write(outWriter.toString());
        out.close();
	}
	
}
